GBML manual / Maths

modulo

What is left over after dividing a by b, and never less than 0: modulo(7, 5) is 2, and modulo(-1, 5) is 4. Use it to make a counter or an angle go round and round - modulo(angle + 10, 360) never leaves 0 up to 360. The % sign and the word mod do the same sum but can give a negative answer (-1 % 5 is -1); modulo does not.

Syntax

modulo(a, b) -> real

Arguments

NameType
areal
breal

Returns

real

Description

What is left over after dividing a by b, and never less than 0. modulo(7, 5) is 2, because 7 is one 5 and 2 more. modulo(-1, 5) is 4: going one step backwards from 0 in a loop of 5 lands on the last place.

Use it to make a counter or an angle go round and round without ever leaving its range. modulo(angle + 10, 360) is always from 0 up to (but not including) 360, whichever way the angle was turned.

Example

var turned = modulo(-30, 360);
var half = modulo(7.5, 2);

turned is 330: 30 degrees backwards from 0 is the same place as 330 degrees forwards. half is exactly 1.5.

Why not just %?

GBML has the % sign and the word mod, and both keep the sign of the number being divided: -1 % 5 is -1. That is awkward for a counter that goes backwards, because -1 is not a place in a loop of 5. modulo fixes it: the answer is always 0 or more and always less than the size of b.

It is also different from wrap. wrap moves a value that has just stepped off one end to the other end in one step; modulo really goes round and round, however far past the end the number is.

The small print

Cost

One divide. Cheap enough to call every frame.

On the GBA

The answer is always 0 or more and always less than the size of b. A b below 0 counts as its size (modulo(7, -5) is 2). A b of 0 has nothing to divide by, so the answer is 0 and the game carries on. It works on the exact 1/4096 steps of a real, so modulo(7.5, 2) is exactly 1.5. It hands back a real; for a counter that must stay a whole number, modulo_int does the same with whole numbers. One divide, cheap enough to call every frame. wrap is different: it jumps from one end of a range to the other in ONE step, where mod really goes round.

See also: modulo_intwrapwrap_intint_floorNumbers